import * as echarts from '../../ec-canvas/echarts';
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ifTeacher: true, //ture 为老师  false为家长身份
    userInfo: {},
    stuIndex:0,
    prescription:{},
    headImg:'',
    ifShowCf:false,//是否显示处方
    cycleId:'',
    testCycleData:[], //体测数据
    middleShow:false,
    studentId:'',

    //素质平均值+等级  assessmentType 1:有氧耐力,2:速度,3:柔韧,4:协调,5: 力量
    assessmentType1:"0",
    assessmentType2:"0",
    assessmentType3:"0",
    assessmentType4:"0",
    assessmentType5:"0",
    assessmentType1Val:"",
    assessmentType2Val:"",
    assessmentType3Val:"",
    assessmentType4Val:"",
    assessmentType5Val:"",

    //雷达图数据
    echartsVal:[],
    echartsValName:[],
    graphEc:{
      lazyLoad: true,
    },

  },

  //雷达图
  initpie:function(){
    let ecComponent = this.selectComponent('#mychart-dom-graph');
    ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
    
      canvas.setChart(chart);

      var option = {
        color: ['#fee3ab', '#FFE434', '#56A3F1', '#FF917C'],
       
        radar: [
          {
            indicator: this.data.echartsValName,
         
            center: ['50%', '50%'],
            radius: 60,
            startAngle: 90,
            splitNumber: 4,
            shape: 'circle',
            axisName: {
              formatter: '{value}',
              color: '#6d6e6e'
            },
            splitArea: {
              areaStyle: {
                color: ['#f76d24', '#fdb932', '#5876f8', '#30ca76'],
                shadowColor: 'rgba(0, 0, 0, 0.2)',
                shadowBlur: 10
              }
            },
            axisLine: {
              lineStyle: {
                color: 'rgba(211, 253, 250, 0)'//0.8
              }
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(211, 253, 250, 0.8)'
              }
            }
          },
        ],
        series: [
          {
            type: 'radar',
            emphasis: {
              lineStyle: {
                width: 4
              }
            },
            data: [
              {
                value: this.data.echartsVal,
              
                areaStyle: {
                  color: 'rgba(255, 228, 52, 0.6)'
                }
              }
            ]
          },
        ]
      };
      chart.setOption(option);
      return chart;
    });
  },




  //弹框选择体测回调方法
  getCycleId(ret){
    console.log("获取数据==="+ret.detail.name);
    console.log("获取数据==="+ret.detail.val);
    this.setData({
      cycleId:ret.detail.val,
      middleShow:false
    })

    if(this.data.ifTeacher){
      this.getTeacherPrescription()
     }else{
      this.getPrescription()
     }
    // this.initpie();
  },

  //周期切换
  showCycleAlert(){
      this.setData({
        middleShow:true
      })
  },

  //处方web详情
  onClickCf(ret){
    console.log('接口数据11a='+ret.currentTarget.dataset.id+"  "+ret.currentTarget.dataset.name)

    if(this.data.ifTeacher){
       this.getTeacherPrescriptionDetail(ret.currentTarget.dataset.id,ret.currentTarget.dataset.name)
    }else{
       this.getPrescriptionDetail(ret.currentTarget.dataset.id,ret.currentTarget.dataset.name)
    }
    
  },

  //提测弹框消失回调
  hiddenAlert(){
    console.log("弹框异常了");
    this.setData({
      middleShow:false
    })
    this.initpie();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      ifTeacher:wx.getStorageSync('ifTeacher'), 
      userInfo:wx.getStorageSync('userData'),
      stuIndex:wx.getStorageSync('stuIndex')
    })
    var ifTeacher = this.data.ifTeacher
    if(ifTeacher){
      var headUrl = "/images/tx.png"
      if(this.data.userInfo.headUrl!=null){
        headUrl = this.data.userInfo.headUrl
      }
      this.setData({
        headImg:headUrl
      })
    }else{
      var tHeadImge = "/images/tx.png"
      if(this.data.userInfo.list!=null && this.data.userInfo.list.length>0 ){    
        if(this.data.userInfo.list[this.data.stuIndex].img !=null){
           tHeadImge = this.data.userInfo.list[this.data.stuIndex].img
        }else{
           if(this.data.userInfo.list[this.data.stuIndex].sex == 1){
             tHeadImge = "/images/tx.png"
           }else{
             tHeadImge = "/images/txn.png"
           }
        }
      }
      this.setData({
        headImg:tHeadImge
      })
    }

    if(options!=null && options.studentId!=null){
      this.setData({
        studentId:options.studentId
      })  
    }else{
      this.setData({
        studentId:this.data.userInfo.list[this.data.stuIndex].studentId
      })
    }
    console.log("studentId="+this.data.studentId+"  "+this.data.ifTeacher);
   this.getTeachCycle()
  },

  
  //头像加载失败
  imgerr(e){
    var tHeadImge = "/images/txn.png"
    if(this.data.userInfo.list!=null && this.data.userInfo.list.length>0 ){    
      if(this.data.userInfo.list[this.data.stuIndex].img !=null){
         tHeadImge = this.data.userInfo.list[this.data.stuIndex].img
      }else{
         if(this.data.userInfo.list[this.data.stuIndex].gender == 1){
           tHeadImge = "/images/tx.png"
         }else{
           tHeadImge = "/images/txn.png"
         }
      }
    }

    this.setData({
      headImg:tHeadImge
    })
  },

  //获取教学周期
  getTeachCycle(){
    var that = this
    wx.showLoading({
      title: '数据加载中...',
      icon: 'none',
    })
  
    app.api.getTeachCycle().then(rest => {
      wx.hideLoading()
      if(rest&&rest.success){   
        console.log('接口数据b='+JSON.stringify(rest.data))

        if(rest.data.list!=null && rest.data.list.length>0){
           that.getTestCycle(rest.data.list[0].key)
        }
      }else{
        console.log('接口数据=='+rest.errMsg)
        wx.showToast({
          title: rest.errMsg||'网络异常，请稍后重试！！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }
    })
    .catch(r => {
      wx.hideLoading()
      console.error(r)
      wx.showToast({
        title: '网络异常，请稍后重试！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    })
  },


  //获取体测周期
  getTestCycle(iTeachCycleId){
    var that = this
    wx.showLoading({
      title: '数据加载中...',
      icon: 'none',
    })
    var datas = {
      teachCycleId:iTeachCycleId,
      type:"2"
    }
    console.log('接口参数='+JSON.stringify(datas))
    app.api.getTestCycle(datas).then(rest => {
      wx.hideLoading()
      if(rest&&rest.success){   
        console.log('接口数据c='+JSON.stringify(rest.data))

        if(rest.data.list!=null && rest.data.list.length>0){
          that.setData({
             testCycleData:rest.data.list,
             cycleId:rest.data.list[0].key
           })

           if(that.data.ifTeacher){
            that.getTeacherPrescription()
           }else{
            that.getPrescription()
           }
           
        }
      }else{
        console.log('接口数据=='+rest.errMsg)
        wx.showToast({
          title: rest.errMsg||'网络异常，请稍后重试！！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }
    })
    .catch(r => {
      wx.hideLoading()
      console.error(r)
      wx.showToast({
        title: '网络异常，请稍后重试！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    })
  },

  //计算素质平均值
  setAssessmentTypeVal(data){
    console.log('处方数据='+JSON.stringify(data))
    var vEchartsVal=[];
    var vEchartsNameVal=[];
    if(data!=null && data.itemQualityMap!=null){
         if(data.itemQualityMap['1'] !=null && data.itemQualityMap['1'].length>0){
            var temp = 0
            for(var j=0;j<data.itemQualityMap['1'].length;j++){
              temp+=parseInt(data.itemQualityMap['1'][j].score)
            }

            temp = temp/data.itemQualityMap['1'].length
            console.log('vAssessmentType1 平均值='+temp)
            vEchartsVal.push(temp);
            const item = {text:"耐力素质: "+temp,max: 100}
            vEchartsNameVal.push(item)
            this.setData({
              assessmentType1:temp
            })
            if(item<60){
               this.setData({
                assessmentType1Val:'需努力'
               })
            }else if(item>=60 && item<80){
              this.setData({
                assessmentType1Val:'合格'
               })
            }else if(item>=80 && item<90){
              this.setData({
                assessmentType1Val:'良好'
               })
            }else{
              this.setData({
                assessmentType1Val:'优秀'
               })
            }
            console.log('vAssessmentType1 ='+this.data.assessmentType1+"  "+this.data.assessmentType1Val)
         }

         if(data.itemQualityMap['2'] !=null && data.itemQualityMap['2'].length>0){
          var temp = 0
          for(var j=0;j<data.itemQualityMap['2'].length;j++){
            temp+=parseInt(data.itemQualityMap['2'][j].score)
          }
          temp = temp/data.itemQualityMap['2'].length
          console.log('vAssessmentType2 平均值='+temp)
          vEchartsVal.push(temp);
          const item = {text:"速度素质: "+temp,max: 100}
          vEchartsNameVal.push(item)
          this.setData({  
            assessmentType2:temp
          })
          if(item<60){
             this.setData({
              assessmentType2Val:'需努力'
             })
          }else if(item>=60 && item<80){
            this.setData({
              assessmentType2Val:'合格'
             })
          }else if(item>=80 && item<90){
            this.setData({
              assessmentType2Val:'良好'
             })
          }else{
            this.setData({
              assessmentType2Val:'优秀'
             })
          }
          console.log('vAssessmentType2 ='+this.data.assessmentType2+"  "+this.data.assessmentType2Val)
       }
      
       if(data.itemQualityMap['3'] !=null && data.itemQualityMap['3'].length>0){
        var temp = 0
        for(var j=0;j<data.itemQualityMap['3'].length;j++){
          temp+=parseInt(data.itemQualityMap['3'][j].score)
        }
        temp = temp/data.itemQualityMap['3'].length
        console.log('vAssessmentType3 平均值='+temp)
        vEchartsVal.push(temp);
        const item = {text:"柔韧素质: "+temp,max: 100}
        vEchartsNameVal.push(item)
        this.setData({
          assessmentType3:temp
        })
        if(temp<60){
           this.setData({
            assessmentType3Val:'需努力'
           })
        }else if(temp>=60 && temp<80){
          this.setData({
            assessmentType3Val:'合格'
           })
        }else if(temp>=80 && temp<90){
          this.setData({
            assessmentType3Val:'良好'
           })
        }else{
          this.setData({
            assessmentType3Val:'优秀'
           })
        }
        console.log('vAssessmentType3 ='+this.data.assessmentType3+"  "+this.data.assessmentType3Val)
     }


     if(data.itemQualityMap['4'] !=null && data.itemQualityMap['4'].length>0){
      var temp = 0
      for(var j=0;j<data.itemQualityMap['4'].length;j++){
        temp+=parseInt(data.itemQualityMap['4'][j].score)
      }
      temp = temp/data.itemQualityMap['4'].length
      console.log('vAssessmentType4 平均值='+temp)
      vEchartsVal.push(temp);
      const item = {text:"灵敏协调素质: "+temp,max: 100}
      vEchartsNameVal.push(item)
      this.setData({
        assessmentType4:temp
      })
      if(temp<60){
         this.setData({
          assessmentType4Val:'需努力'
         })
      }else if(temp>=60 && temp<80){
        this.setData({
          assessmentType4Val:'合格'
         })
      }else if(temp>=80 && temp<90){
        this.setData({
          assessmentType4Val:'良好'
         })
      }else{
        this.setData({
          assessmentType4Val:'优秀'
         })
      }
      console.log('vAssessmentType4 ='+this.data.assessmentType4+"  "+this.data.assessmentType4Val)
    }

    if(data.itemQualityMap['5'] !=null && data.itemQualityMap['5'].length>0){
      var temp = 0
      for(var j=0;j<data.itemQualityMap['5'].length;j++){
        temp+=parseInt(data.itemQualityMap['5'][j].score)
      }
      temp = temp/data.itemQualityMap['5'].length
      console.log('vAssessmentType5 平均值='+temp)
      vEchartsVal.push(temp);
      const item = {text:"力量素质: "+temp,max: 100}
      vEchartsNameVal.push(item)
      this.setData({
        assessmentType5:temp
      })
      if(temp<60){
         this.setData({
          assessmentType5Val:'需努力'
         })
      }else if(temp>=60 && temp<80){
        this.setData({
          assessmentType5Val:'合格'
         })
      }else if(temp>=80 && temp<90){
        this.setData({
          assessmentType5Val:'良好'
         })
      }else{
        this.setData({
          assessmentType5Val:'优秀'
         })
      }
      console.log('vAssessmentType5 ='+this.data.assessmentType5+"  "+this.data.assessmentType5Val)
    }
    }
    this.setData({
      echartsVal:vEchartsVal,
      echartsValName:vEchartsNameVal
    })
    this.initpie();
  },

 //学生运动处方
 getPrescription(){
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })

  var data = {
    cycleId:this.data.cycleId,
    studentId:this.data.studentId,
  }
  console.log('接口参数='+JSON.stringify(data))
  app.api.getPrescription(data).then(rest => {
    wx.hideLoading()
    if(rest&&rest.success){   
      console.log('接口数据a='+JSON.stringify(rest.data))
      
      var vIfShowCf = false
      if(rest.data.studentPrescriptionList!=null && rest.data.studentPrescriptionList.length>0){
        vIfShowCf = true
      }else{
        vIfShowCf = false
      }
      this.setData({
        prescription:rest.data,
        ifShowCf:vIfShowCf
      })
      this.setAssessmentTypeVal(rest.data)
    }else{
      console.log('接口数据wwww=='+rest.errMsg)
      wx.showToast({
        title: '网络异常，请稍后重试！！',
        icon: 'none',
        duration: 800,
        mask:true,
        complete: function (res) {
          setTimeout(function(){
            wx.navigateBack({
              delta: 1,  // 返回上一级页面。
              success: function() {           
              }
            })
          },800)
        }
      })
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},


//学生运动处方
getPrescriptionDetail(prescriptionId,prescriptionName){
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })

  var data = {
    prescriptionId:prescriptionId
  }
  console.log(prescriptionId+"  "+prescriptionName+' 接口参数='+JSON.stringify(data))
  app.api.getPrescriptionDetail(data).then(rest => {
    wx.hideLoading()
    if(rest&&rest.success){   
      console.log('接口数据ak='+rest.data)
      wx.setStorageSync('cfurl', rest.data)
      wx.navigateTo({
        url: '/pages/outer/outer?webUrl=cfurl&cfname='+prescriptionName,
      })
      
    }else{
      console.log('接口数据dd=='+rest.errMsg)
      wx.showToast({
        title: '网络异常，请稍后重试！！',
        icon: 'none',
        duration: 800,
        mask:true,
        complete: function (res) {
          setTimeout(function(){
            wx.navigateBack({
              delta: 1,  // 返回上一级页面。
              success: function() {           
              }
            })
          },800)
        }
      })
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},


 //学生运动处方
 getTeacherPrescription(){
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })

  var data = {
    cycleId:this.data.cycleId,
    studentId:this.data.studentId,
  }
  console.log('老师111接口参数='+JSON.stringify(data))
  app.api.getTeacherPrescription(data).then(rest => {
    wx.hideLoading()
    console.log('接口数据ab='+JSON.stringify(rest))
    if(rest&&rest.success){   
      //console.log('接口数据a='+JSON.stringify(rest.data))
      
      var vIfShowCf = false
      if(rest.data.studentPrescriptionList!=null && rest.data.studentPrescriptionList.length>0){
        vIfShowCf = true
      }else{
        vIfShowCf = false
      }
      this.setData({
        prescription:rest.data,
        ifShowCf:vIfShowCf,
        headImg:rest.data.img
      })
      this.setAssessmentTypeVal(rest.data)
    }else{
      console.log('接口数据xxxsss=='+rest.errMsg)
      wx.showToast({
        title: rest.errMsg||'网络异常，请稍后重试！！',
        icon: 'none',
        duration: 800,
        mask:true,
        complete: function (res) {
          setTimeout(function(){
            wx.navigateBack({
              delta: 1,  // 返回上一级页面。
              success: function() {           
              }
            })
          },800)
        }
      })
     
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},


//老师学生运动处方
getTeacherPrescriptionDetail(prescriptionId,prescriptionName){
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })

  var data = {
    prescriptionId:prescriptionId
  }
  console.log(prescriptionId+"  "+prescriptionName+' 老师接口参数='+JSON.stringify(data))
  app.api.getTeacherPrescriptionDetail(data).then(rest => {
    wx.hideLoading()
    if(rest&&rest.success){   
      console.log('接口数据ak='+rest.data)
      wx.setStorageSync('cfurl', rest.data)
      wx.navigateTo({
        url: '/pages/outer/outer?webUrl=cfurl&cfname='+prescriptionName,
      })
      
    }else{
      console.log('接口数据=='+rest.errMsg)
      wx.showToast({
        title: rest.errMsg||'网络异常，请稍后重试！！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})